#!/usr/bin/env python3

import json

import pymongo
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options

import constants

from tornado.options import define, options

from modules import *
from handlers import *


define('port', default=8000, help='server port', type=int)
define('mongo', default=None, help='mongodb uri', type=str)
define('database', default='KnownsecWebsite', help='database name', type=str)


routes = [
    (r'/', HomeHandler),
    (r'/auth/([0-9a-fA-F]+)', AuthManageHandler),
    (r'/auth/create', AuthCreateHandler),
    (r'/auth/login', AuthLoginHandler),
    (r'/auth/logout', AuthLogoutHandler),
    (r'/auth/forget_pass', AuthForgetPassHandler),
    (r'/auth/recovery', AuthRecoveryHandler),
    (r'/auth/update_pass', AuthUpdatePassHandler),
    (r'/entry/edit', EntryEditHandler),
    (r'/entry/delete/([0-9a-fA-F]+)', EntryDeleteHandler),
    (r'/entry/show/([0-9a-fA-F]+)', EntryShowHandler),
    (r'/entry/comment', EntryCommentHandler),
]


class Application(tornado.web.Application):
    def __init__(self, mongo_uri, database, routes):
        settings = dict(
            template_path=constants.TEMPLATE_PATH,
            static_path=constants.STATIC_PATH,
            ui_modules={
                "Comment": CommentModule,
                "Entry": EntryModule,
                "Modal": ModalModule,
            },
            xsrf_cookie=True,
            cookie_secret='KzsqWNH3FzH3AFWRAxXmMHSJf9P4lnyxRhHvTq2fIEA=',
            login_url=r'/auth/login',
            # debug=True,
        )
        self.db = pymongo.MongoClient(mongo_uri)[database]
        tornado.web.Application.__init__(self, routes, **settings)


if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = Application(options.mongo, options.database, routes)
    server = tornado.httpserver.HTTPServer(app)
    server.listen(options.port)
    loop = tornado.ioloop.IOLoop.instance()
    try:
        print('[+] Running on port %d' % options.port)
        loop.start()
    except KeyboardInterrupt:
        loop.stop()
        print('\rBye~')
